import axios from 'axios'
import request, { uploadInstance } from '@/utils/request.js'


//获取验证码图片
export function getVerifyCode() {
  return request.get('/verify/code/createShearCaptcha', { responseType: 'arraybuffer' });
}

// 验证验证码
export function verifyCode(code) {
  return request.post('/verify/code/verify', { code: code.toLowerCase() })
}

// 提交信息
export function submitReport(department, formData, onProgress) {
  // 创建请求取消令牌
  const controller = new AbortController();
  const signal = controller.signal;
  
  // 使用无超时限制的实例进行文件上传
  const request = uploadInstance({
    url: `/reports/submit/${department}`,
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    signal: signal,
    // 上传进度事件
    onUploadProgress: progressEvent => {
      if (onProgress && progressEvent.total) {
        // 计算上传进度百分比
        const percentage = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        onProgress(percentage)
      }
    }
  });
  
  // 设置一个超时保障，以防止请求无限挂起
  const safetyTimeout = setTimeout(() => {
    // 如果请求超过5分钟，强制中断
    controller.abort('请求超时，已自动中断');
  }, 5 * 60 * 1000); // 5分钟超时
  
  // 确保请求完成后清除超时定时器
  return request.finally(() => {
    clearTimeout(safetyTimeout);
  });
}

// 获取部门名称
export function getDepartmentName(department) {
  const departmentMap = {
    'medical': '区医保局',
    'petition': '区信访局',
    'education': '区教体局'
  }
  return departmentMap[department] || '区医保局'
}

export default {
  submitReport,
  getDepartmentName,
  getVerifyCode,
  verifyCode
} 